#include "basic/url.h"
#include "basic/log.h"

NS_USE_STD

namespace basic {
/**
 * TODO:Jerry:this implementation needs to improve efficiency
 * use regular expression instead.
 */
DKURL::DKURL() {
}
DKURL::DKURL(const DKURL& another) : DKURL(another.m_sURL) {
}

DKURL::DKURL(const char* url) : DKURL(std::string(url)) {
}

DKURL::DKURL(const std::string& url) {
  _Set(url);
}

DKURL& DKURL::operator=(const DKURL& another) {
  _Set(another.m_sURL);
  return *this;
}

bool DKURL::Set(const DKURL& another) {
  _Set(another.m_sURL);
  return true;
}
bool DKURL::Set(const std::string& str) {
  _Set(str);
  return true;
}
bool DKURL::Set(const char* charstar) {
  _Set(std::string(charstar));
  return true;
}

const std::string& DKURL::GetURL() const {
  return m_sURL;
}

std::string DKURL::GetPath() const {
  if (m_iLastSlashIndexPlusOne >= 0) {
    return m_sURL.substr(0, m_iLastSlashIndexPlusOne);
  }
  M_LOG_ERROR("not a valid path.")
  return "";
}

std::string DKURL::GetName() const {
  if (m_iLastSlashIndexPlusOne >= 0) {
    return m_sURL.substr(m_iLastSlashIndexPlusOne);
  }
  M_LOG_ERROR("not a valid path.")
  return "";
}

std::string DKURL::GetStem() const {
  std::string name = GetName();
  auto pos = name.find_last_of('.');
  if (pos >= 0) {
    return name.substr(0, pos);
  }
  return "";
}

std::string DKURL::GetExtension() const {
  std::string name = GetName();
  auto pos = name.find_last_of('.');
  if (pos >= 0) {
    return name.substr(pos);
  }
  return "";
}

bool DKURL::IsValidURL() const {
  return m_sURL != "";
}

void DKURL::_Set(const std::string& url) {
  /// TODO: use regular expression;
  const auto N{url.length()};
  m_sURL.resize(N);
  for (size_t i = 0; i < N; ++i) {
    if (url[i] == '\\') {
      m_sURL[i] = '/';
    } else {
      m_sURL[i] = url[i];
    }
  }
  m_iLastSlashIndexPlusOne = m_sURL.find_last_of('/') + 1;
}
}
